<!-- 课程详情 -->
<script setup lang="ts">
import MpHtml from 'mp-html/src/uni-app/components/mp-html/mp-html.vue'
import { useRequest } from 'vue-request'
import { fetchClassDetailAPI } from '@/apis/fetchClassDetail'
import { useUserInfoStore } from '@/store/userInfo'
import { registerAPI } from '@/apis/register'
import { fetchClassDetailWithoutTokenAPI } from '@/apis/fetchClassDetailWithoutToken'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 班级 id
const classId = ref('')

// request
const { data, loading, run } = useRequest(fetchClassDetail, {
  loadingDelay: 300,
  loadingKeep: 1000,
})

// 班级详情数据
const classDetail = computed(() => {
  return data.value?.data?.data
})

const buttonLabel = computed(() => {
  if (classDetail.value?.is_entry)
    return classDetail.value.is_report ? '已报名' : '立即报名'
  else
    return '报名已结束'
})

// 请求服务函数
function fetchClassDetail() {
  if (userInfoStore.userInfo && userInfoStore.userInfo.token)
    return fetchClassDetailAPI(classId.value, userInfoStore.userInfo!.token!)
  else
    return fetchClassDetailWithoutTokenAPI(classId.value)
}

onLoad(async (options) => {
  if (options && options.id) {
    classId.value = options.id
    run()
  }
  else { uni.showToast({ title: '数据获取失败', icon: 'none' }) }
})
onShow(() => run())

onShareAppMessage(() => {
  return {
    title: '班级详情',
    path: `pages/classDetail?id=${classId.value}`,
  }
})

onShareTimeline(() => {
  return {
    title: '班级详情',
    path: `pages/classDetail?id=${classId.value}`,
  }
})

const isShowDialog = ref(false)

function isNeedLogin() {
  if (!(userInfoStore.userInfo && userInfoStore.userInfo?.user_id))
    return true
  else
    return false
}

/**
 * @description 点击“为他人报名”按钮时触发
 */
function handleRegisterForSomeone() {
  if (isNeedLogin()) {
    router.push({
      name: 'login',
      params: {
        abnormal: 'true',
      },
    })
    return
  }

  // 如果班级已经不允许报名
  if (!classDetail.value?.is_entry) {
    uni.showToast({ title: '报名已结束', icon: 'none' })
    return
  }

  router.push({
    name: 'registerForSomeone',
    params: {
      class_id: classDetail.value?.id.toString() || '',
      class_name: classDetail.value?.title || '',
    },
  })
}

/**
 * @description 点击“立即报名”按钮时触发
 */
function handleRegister() {
  if (isNeedLogin()) {
    router.push({
      name: 'login',
      params: {
        abnormal: 'true',
      },
    })
    return
  }

  // 如果班级已经不允许报名
  if (!classDetail.value?.is_entry) {
    uni.showToast({ title: '报名已结束', icon: 'none' })
    return
  }

  // 如果已经报过名，就不报了，弹窗提示
  if (classDetail.value?.is_report) {
    uni.showToast({ title: '您已报名，请勿重复报名', icon: 'none' })
    return
  }

  // 打开确认窗口
  isShowDialog.value = true
}

/**
 * @description 在确认报名的窗口中点击“确认”按钮时触发
 */
async function handleConfirm() {
  try {
    const res = await registerAPI(
      { id: classDetail.value!.id!.toString()! },
      userInfoStore.userInfo!.token!,
    )
    if (res.data?.code === 1) {
      router.replace({
        name: 'submitSuccess',
        params: { type: '报名' },
      })
    }
    else { uni.showToast({ title: res.data?.msg, icon: 'none' }) }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}
</script>

<template>
  <view class="absolute left-0 top-0 z-0">
    <!-- 背景主图 -->
    <uv-image :src="withDomain(classDetail?.images || '')" width="750rpx" height="529rpx" />
  </view>
  <view class="relative z-1">
    <Spacer height="475" />
    <!-- 标题卡片 START -->
    <view class="rounded-20rpx bg-white px-25rpx pb-25rpx pt-20rpx card-shadow">
      <view class="text-36rpx text-#333333 font-medium leading-50rpx">
        {{ classDetail?.title || '未知标题' }}
      </view>
      <Spacer height="20" />
      <Divider width="650" />
      <Spacer height="20" />
      <view>
        <!-- 机构 -->
        <view class="flex items-center">
          <image src="../static/images/building.png" class="h-24rpx w-24rpx flex-shrink-0" />
          <Spacer width="16" />
          <view class="h-32rpx overflow-hidden text-ellipsis text-24rpx text-#666666 leading-32rpx">
            {{ classDetail?.place || '未知' }}
          </view>
        </view>
        <Spacer height="12" />
        <!-- 时间 -->
        <view class="flex items-center">
          <image src="../static/images/clock.png" class="h-24rpx w-24rpx flex-shrink-0" />
          <Spacer width="16" />
          <view class="h-32rpx overflow-hidden text-ellipsis text-24rpx text-#666666 leading-32rpx">
            {{ classDetail?.start_time || '未知时间' }}
          </view>
        </view>
      </view>
    </view>
    <!-- 标题卡片 END -->
    <Spacer height="20" />
    <!-- 简介卡片 START -->
    <view class="rounded-20rpx bg-white px-25rpx pb-40rpx pt-30rpx card-shadow">
      <view class="flex">
        <view class="relative">
          <view class="text-32rpx text-#333333 font-semibold leading-32rpx">
            课程简介
          </view>
          <view class="absolute bottom-0 h-10rpx w-full from-#0037AE to-#0037AE from-opacity-10 bg-gradient-to-r" />
        </view>
      </view>
      <Spacer height="24" />
      <view class="text-26rpx text-#666666 leading-40rpx">
        <MpHtml :content="classDetail?.content || '未知内容'" />
      </view>
    </view>
    <!-- 简介卡片 END -->
    <Spacer height="240" />
  </view>
  <view class="fixed bottom-0 z-10 h-168rpx w-750rpx flex items-center bg-white pb-48rpx x-center">
    <Spacer width="25" />
    <button class="h-100rpx w-180rpx flex items-center justify-center rounded-full bg-#F4F4F4 text-24rpx text-#919191 font-medium leading-32rpx" hover-class="bg-#E9E9E9" @tap="handleRegisterForSomeone">
      {{ classDetail?.is_entry ? '为他人报名' : '报名已结束' }}
    </button>
    <Spacer width="12" />
    <button
      class="h-100rpx w-482rpx flex items-center justify-center rounded-full bg-#0037AE text-30rpx text-white font-medium leading-42rpx"
      :class="[Boolean(classDetail?.is_report) ? 'opacity-40' : '']"
      hover-class="bg-#3266D9"
      @tap="handleRegister"
    >
      {{ buttonLabel }}
    </button>
  </view>
  <uv-overlay :show="isShowDialog" @tap="isShowDialog = false">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <view class="absolute left-50% top-50% -translate-50%">
          <Dialog
            title="立即报名"
            cancel-label="再想想"
            confirm-label="确认报名"
            @cancel="isShowDialog = false"
            @confirm="handleConfirm"
          >
            <div class="px-40rpx text-center">
              您即将报名 {{ classDetail?.title }} 该课程，请立即确认
            </div>
          </Dialog>
        </view>
      </view>
    </uv-transition>
  </uv-overlay>
  <uv-loading-page :loading="loading" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />
</template>

<route lang="yaml">
name: 'classDetail'
style:
  navigationBarTitleText: '班级详情'
</route>
